//
//  HomeModel.m
//  CherryPlumStore
//
//  Created by SDX on 2019/9/22.
//  Copyright © 2019 千凯. All rights reserved.
//

#import "HomeLoader.h"
#import "Http.h"
#import "ActivitysModel.h"
#import "SwiperModel.h"

@interface HomeLoader()

-(void) configWithDic: (NSDictionary *)dic;

-(void) configActivies:(NSArray *) actives;

@end

@implementation HomeLoader
/**
 加载数据并序列化 然后block回调

 @param finishBlock 成功返回数据
 */
-(void)loadDataWithFinishBlock:(LoadHomePageBlock)finishBlock {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
#pragma -mark 这里要进行本地数据读取
    [params setObject:@"888888" forKey:@"token"];
    [params setObject:@"1" forKey:@"currPage"];
    [params setObject:@"0" forKey:@"pageSize"];
    
    [Http getWithUrl:@"app/main/index" WithParams:params WithSuccessBlock:^(id result) {
        NSString *code = [result objectForKey:@"code"];
        NSDictionary *data = [result objectForKey:@"data"];
        if ([code isEqualToString:@"1"]) {
            // 调用数据格式化方法
            [self configWithDic:data];
            // 将数据返回controller
            dispatch_async(dispatch_get_main_queue(), ^{
                if (finishBlock) {
                    finishBlock(YES, self.homeData.copy);
                }
            });
        }
    } WithFailBlock:^(NSString *errResult) {
        NSLog(@"err=>%@", errResult);
    }];
}

/**
 数据的序列化

 @param dic 整个首页的data
 */
- (void)configWithDic:(NSDictionary *)dic {
    // 初始化一下
    _homeData = [NSMutableDictionary dictionary];

    // 获取首页数据中的活动列表, 并且将数据格式化
    NSArray *actives= [dic objectForKey:@"activitys"];
    // 获取轮播图的数据
    NSArray *swipers = [dic objectForKey:@"carouselfigs"];
    
    [self configSwipers:swipers];
    [self configActivies: actives];
}


/**
 格式化轮播图

 @param swipers 轮播图
 */
-(void) configSwipers:(NSArray *)swipers {
    NSMutableArray<SwiperModel *> *swipersArr = @[].mutableCopy;
    for (NSDictionary *swiper in swipers) {
        SwiperModel *swiperModel = [[SwiperModel alloc] init];
        [swiperModel configWithDic: swiper];
        [swipersArr addObject:swiperModel];
    }
    [_homeData setValue:swipersArr forKey:@"swipers"];
}

/**
 格式化活动列表

 @param actives 活动列表
 */
- (void)configActivies:(NSArray *)actives {
    NSMutableArray<ActivitysModel *> *activeArr = @[].mutableCopy;
    for (NSDictionary *active in actives) {
        ActivitysModel *activeModel = [[ActivitysModel alloc] init];
        [activeModel configWithDic:active];
        [activeArr addObject:activeModel];
    }
    [_homeData setValue:activeArr forKey:@"actives"];
}

@end
